// pages/kuaidi/index.js
const App = getApp();
import Toast from '@vant/weapp/toast/toast';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 优惠券列表
    list: [],
    // show
    notcont: false,
    active: 0,
    showBox: false,
    statusBarHeight: getApp().globalData.statusBarHeight,
    area_name: '',
    site: [],
    category: [],
    displayTime: false,
    currentDate: new Date().getTime(),
    minHour: new Date().getHours(),
    minMinute: new Date().getMinutes(),
    site_index: '',
    category_index: '',
    give_time: '',
    give_type: [], //配送类型
    time_index: '',
    total: 0,
    coupon: [],
    coupon_index: '',
    reduce_price: 0.00,
    userInfo: [],
    setting: [],
    use_balance: false,
    use_points: false,
    message: '' //短信内容
  },
  onClipboardBtn(e) {
    let _this = this
    _this.onClipboard(e.currentTarget.dataset.id)
  },
  onClipboard(type) {
    let _this = this
    wx.getClipboardData({
      success(res) {
        _this.setData({
          message: type == 1 ? res.data : ''
        })
      }
    })
  },
  onButtonSubmit(e) {
    let _this = this
    // 短信内容
    let message = _this.data.message
    // 快递类型
    let site_id = (_this.data.site && _this.data.site_index) ? _this.data.site[_this.data.site_index].site_id : 0
    // 包裹重量
    let price_id = (_this.data.category && _this.data.category_index) ? _this.data.category[_this.data.category_index].price_id : 0
    // 派送时间 
    let give_time = (_this.data.give_type && _this.data.time_index) ? _this.data.give_type[_this.data.time_index].name : ''
    // 优惠券
    let coupon_id = (_this.data.coupon && _this.data.coupon_index) ? _this.data.coupon[_this.data.coupon_index].user_coupon_id : 0
    // 个人收货地址
    let address_default = _this.data.userInfo.address_default
    let obj = {
      area_id: _this.data.area.area_id,
      message: message,
      site_id: site_id,
      price_id: price_id,
      give_time: give_time,
      coupon_id: coupon_id,
      coupon_money: _this.data.reduce_price,
      total_price: _this.data.total / 100,
      pay_price: _this.data.total / 100,
      address: _this.data.area_name,
      address_default: address_default
    }
    let arr = [{
        data: address_default,
        err: '收件地址必选'
      }, {
        data: message,
        err: '取件内容必填'
      },
      {
        data: site_id,
        err: '快递类型必选'
      },
      {
        data: price_id,
        err: '包裹重量必选'
      },
      {
        data: give_time,
        err: '派送时效必选'
      }
    ]
    for (let i in arr) {
      if (!arr[i].data) {
        Toast({
          type: 'fail',
          forbidClick: true,
          message: arr[i].err,
          onClose: () => {
            console.log('执行OnClose函数');
          },
        });
        return
      }
    }
    // 提交订单
    _this.createdOrder(obj)
  },
  createdOrder(postData) {
    App._post_form('kuaidi.order/created', postData, result => {
      if (result.code == 1) {
        App.wxPayment({
          payment: result.data.payment,
          success: res => {
            wx.navigateTo({
              url: '/pages/user/kuaidi/order',
            })
          },
          fail: res => {
            App.showError(result.msg.error, () => {});
          },
        });
      }
    });
  },
  onChangeMessage(e) {
    let _this = this
    _this.setData({
      message: e.detail.value
    })
  },
  onChangeBalance({
    detail
  }) {
    let _this = this
    this.setData({
      use_balance: detail
    });
  },
  onChangePoints({
    detail
  }) {
    let _this = this
    this.setData({
      use_points: detail
    });
    let points = _this.data.userInfo ? _this.data.userInfo.points : 0
    let exchange_points = _this.data.setting.use_points.exchange_points
    _this.onExchangeTotal(detail, (points / exchange_points))
  },
  onExchangeTotal(is_use, total) {
    let _this = this
    total = total * 100
    if (!_this.data.total) {
      this.setData({
        use_points: false,
        use_balance: false
      });
      return false
    }
    if (is_use) {
      _this.setData({
        total: _this.data.total - total
      })
      return false
    }
    _this.setData({
      total: _this.data.total + total
    })
  },
  /**
   * 获取公告信息
   */
  getKuaidiSetting() {
    let _this = this;
    App._get('kuaidi.index/getKuaidiSetting', {}, function (result) {
      _this.setData({
        setting: result.data
      })
      _this.getGiveType()
    });
  },
  getGiveType() {
    let _this = this;
    let give_type = _this.data.setting.give_time
    let obj = []
    obj[0] = {
      name: give_type.timely.name,
      value: give_type.timely.value
    }
    obj[1] = {
      name: give_type.focus.name,
      value: give_type.focus.value
    }
    _this.setData({
      give_type: obj
    })
  },
  /**
   * 获取当前用户信息
   */
  getUserDetail() {
    let _this = this;
    App._get('user.index/detail', {}, function (result) {
      _this.setData({
        userInfo: result.data.userInfo
      });
    });
  },
  /**
   * 获取优惠券列表
   */
  getCouponList: function () {
    let _this = this;
    App._get('coupon/lists', {}, function (result) {
      _this.setData({
        list: result.data.list,
        notcont: !result.data.list.length
      });
    });
  },
  bindChangeCoupon(e) {
    let _this = this
    if (!_this.data.coupon.length) {
      return
    }
    _this.setData({
      coupon_index: e.detail.value
    })
    _this.calcTotal()
  },
  bindChangeSite(e) {
    let _this = this
    _this.setData({
      site_index: e.detail.value
    })
  },
  bindChangeCategory(e) {
    let _this = this
    _this.setData({
      category_index: e.detail.value
    })
    _this.getCoupon()
  },
  adress() {
    wx.navigateTo({
      url: '/pages/address/index?from=flow',
    })
  },
  toLocation() {
    wx.navigateTo({
      url: '/kuaidi/pages/location/index',
    })
  },
  onShowBox: function () {
    let _this = this
    _this.setData({
      showBox: true
    })
  },
  onCloseBox: function () {
    let _this = this
    _this.setData({
      showBox: false
    })
  },
  getSite() {
    let _this = this;
    App._get('kuaidi.index/site', {
      area_id: _this.data.area && _this.data.area.area_id
    }, result => {
      _this.setData({
        site: result
      })
    });
  },
  getCategory() {
    let _this = this;
    App._get('kuaidi.index/category', {
      area_id: _this.data.area && _this.data.area.area_id
    }, result => {
      _this.setData({
        category: result
      })
    });
  },
  bindGiveTime(e) {
    let _this = this
    _this.setData({
      time_index: e.detail.value
    })
    _this.calcTotal()
  },
  getToTime() {
    let _this = this
    _this.setData({
      displayTime: !_this.data.displayTime
    })
  },
  onConfirmTime(e) {
    let _this = this
    _this.setData({
      give_time: e.detail
    })
    _this.getToTime()
  },
  getCoupon() {
    let _this = this;
    App._get('kuaidi.index/getCoupon', {
      total: _this.data.total
    }, result => {
      _this.setData({
        coupon: result.data
      })
      _this.calcTotal()
    });
  },
  calcTotal() {
    let _this = this
    let money = (_this.data.category && _this.data.category_index) ? _this.data.category[_this.data.category_index].money : 0
    if (_this.data.give_type && _this.data.time_index != '') {
      money = parseFloat(money) + parseFloat(_this.data.give_type[_this.data.time_index].value)
    }
    if (_this.data.coupon.length && _this.data.coupon_index != '') {
      let reduce_price = _this.data.coupon ? _this.data.coupon[_this.data.coupon_index].reduce_price : 0
      let min_price = _this.data.coupon ? _this.data.coupon[_this.data.coupon_index].min_price : 0
      let total = (money >= min_price) ? (money - reduce_price) : money
      _this.setData({
        total: total * 100,
        reduce_price: reduce_price
      })
      return false;
    }
    _this.setData({
      total: money * 100
    })
  },
  /**
   * 领取优惠券
   * @param {*} e 
   */
  receive: function (e) {
    let _this = this,
      couponId = e.currentTarget.dataset.couponId;

    App._post_form('user.coupon/receive', {
      coupon_id: couponId
    }, function (result) {
      App.showSuccess(result.msg);
      // 获取优惠券列表
      _this.getCouponList();
    });

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let _this = this
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let _this = this
    let area = wx.getStorageSync('area')
    if (area && (area = JSON.parse(area))) {
      _this.setData({
        area: area,
        area_name: area.name
      })
    }
    let kuaidi = App.getWxappByKey('kuaidi')
    // 设置公告信息
    _this.setData({
      notice: kuaidi && kuaidi.values.notice
    })
    // 获取站点
    _this.getSite()
    // 获取包裹类型价格
    _this.getCategory()
    // 如果选择了价格，则直接获取优惠券
    _this.data.category_index && _this.getCoupon()
    // 领券大厅
    _this.getCouponList()
    // 获取用户信息
    _this.getUserDetail()
    // 获取快递设置
    _this.getKuaidiSetting()
    // 粘贴板
    _this.onClipboard(1)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    const _this = this;
    // 构建页面参数
    const params = App.getShareUrlParams({});
    return {
      title: '10秒快速下单，5分钟快递到手',
      path: "/pages/kuaidi/index?" + params,
      imageUrl: "/images/mini-cover.jpg"
    };
  }
})